package com.im.server.handle.impl;
import com.im.server.handle.MessageService;
import com.im.server.protocol.MessageProto;
import com.im.web.core.model.ChatMessage;
import com.im.web.core.repository.ChatMessageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.im.common.Constants.CommandType.MESSAGE;
import static com.im.common.Constants.TO_SERVER;

/**
 * @author gongym
 * @date 2019/1/20 13:06
 */
@Component("ServerMessageServiceImpl")
public class ServerMessageServiceImpl implements MessageService {
	private final ChatMessageRepository chatMessageRepository;
	@Autowired public ServerMessageServiceImpl(ChatMessageRepository chatMessageRepository) {
		this.chatMessageRepository = chatMessageRepository;
	}
	@Override
  public MessageProto.MessageProtocol handleMessage(MessageProto.MessageProtocol messageProtocol) {
  	// 存储数据库
		ChatMessage fromChatMessage = new ChatMessage();
		fromChatMessage.setFromId(messageProtocol.getFrom());
		fromChatMessage.setToId(messageProtocol.getTo());
		fromChatMessage.setChatType(messageProtocol.getType());
		fromChatMessage.setCreateTime(new Date(messageProtocol.getCreateTime()));
		fromChatMessage.setChatContent(messageProtocol.getContent());
		chatMessageRepository.save(fromChatMessage);
    return MessageProto.MessageProtocol.newBuilder()
        .setFrom(TO_SERVER)
        .setTo(messageProtocol.getFrom())
        .setCreateTime(System.currentTimeMillis())
        .setContent(messageProtocol.getContent())
        .setType(MESSAGE)
        .build();
  }
}
